package com.lagou.service;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 13771
 * @date 2020/9/6 1:57
 * @description
 */
@Component
public class ZkConfig implements Runnable{
    @Override
    public void run() {
        //注册服务
        ZkClient zkClient = new ZkClient("127.0.0.1:2181",2000,5000);
        String root = "/rpcServer";
        if (!zkClient.exists(root)){
            //如果父节点不存在，先创建父节点
            zkClient.createPersistent(root);  //父节点是持久节点
        }

        //注册监听
        zkClient.subscribeChildChanges(root, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {

                System.out.println(parentPath+"父节点下注册的服务列表为："+currentChilds);
            }
        });

        //创建子节点
        String nodeName = root + "/service2";
        String nodeValue = "127.0.0.1:8999";
        if (zkClient.exists(nodeName)){
            zkClient.delete(nodeName);
        }
        zkClient.createEphemeral(nodeName,nodeValue);

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
